from django.core.cache import cache
from rest_framework import viewsets
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
from rest_framework.views import APIView
import logging

from home.models import Gps, Course, Img, Tupian
from home.serializer import GpsSerializer, CourseSerializer, ImgSerializer, TupianSerializer

logger =logging.getLogger('django')

# Create your views here.
class GpsView(APIView):
    def get(self,request):
        logger.info('fffff')
        queryset = Gps.objects.filter(is_show=True,is_delete=False)
        ser = GpsSerializer(queryset,many=True)
        return Response({'code':1,'msg':'ok','data':ser.data})


class CourseView(APIView):
    def get(self,request):
        queryset = Course.objects.filter(is_show=True,is_delete=False,level='1')
        ser= CourseSerializer(queryset,many=True)
        return Response({'code':1,'msg':'ok','data':ser.data})


class ImgView(APIView):
    def get(self,request):
        try:
            cache_key = 'day01:home:img:list'
            img_list = cache.get(cache_key)
            if img_list:
                logger.info('从缓存中获取图片数据')
                return Response({'code':1,'msg':'从缓存中获取图片数据','data':img_list})
            queryset = Img.objects.filter(is_show=True,is_delete=False)
            ser = ImgSerializer(queryset,many=True)

            # 用mysql查完后，存入缓存
            cache.set(cache_key,ser.data,60*60*24)
            logger.info(f'一共{len(ser.data)}条数据')
            return Response({'code':1,'msg':'从mysql中获取数据，并存入缓存','data':ser.data})
        except Exception as e:
            logger.error(f'获取图片数据失败:{e}')
            return Response({'code':0,'msg':'获取图片数据失败','data':[]})

class Page(PageNumberPagination):
    page_size = 10
    page_size_query_param = 'size'
    page_query_param = 'page'
#定义视图集

class TupianView(viewsets.ModelViewSet):
    queryset = Tupian.objects.all()
    serializer_class = TupianSerializer
    pagination_class = Page








































